package com.command.center.pucms.common.exception;

import com.command.platform.core.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义权限异常
     * @param e
     * @return
     */
    @ExceptionHandler({AuthorizationException.class})
    public Result globalAuthorizationExceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return Result.failure(e.getMessage(),null);
    }

    /**
     * 处理shiro异常
     * @param e
     * @return
     */
    @ExceptionHandler({ShiroException.class})
    public Result globalShiroExceptionHandler(Exception e) {
        String message = e.getMessage();
        log.error(e.getMessage(), e);
        if (e instanceof UnknownAccountException){
            message = "用户不存在";
        }
        if (e instanceof IncorrectCredentialsException){
            message = "用户名无效";
        }
        if (e instanceof AuthenticationException){
            message = "密码错误";
        }
        if (e instanceof UnauthorizedException){
            message = "权限不足";
        }
        if (e instanceof UnauthenticatedException){
            message = "token不合法";
        }
        return Result.failure(message,null);
    }

    /**
     * 处理全部异常
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class})
    public Result globalExceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return Result.failure(e.getMessage(),null);
    }
}
